package com.hongmeng.web.controller.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.hongmeng.common.utils.MessageUtils;
import com.hongmeng.common.utils.SecurityUtils;
import com.hongmeng.web.ueditor.ActionEnter;
import com.hongmeng.operater.domain.HmFile;
import com.hongmeng.operater.mapper.HmFileMapper;
import com.hongmeng.operater.service.impl.HmFileServiceImpl;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.hongmeng.common.config.HongMengConfig;
import com.hongmeng.common.constant.Constants;
import com.hongmeng.common.core.domain.AjaxResult;
import com.hongmeng.common.utils.StringUtils;
import com.hongmeng.common.utils.file.FileUploadUtils;
import com.hongmeng.common.utils.file.FileUtils;
import com.hongmeng.framework.config.ServerConfig;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author hongmeng
 */
@Api("通用请求")
@RestController
@Slf4j
public class CommonController
{
    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private FileUploadUtils fileUploadUtils;

    @Autowired
    private HmFileMapper hmFileMapper;

    @Autowired
    private HmFileServiceImpl hmFileService;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = HongMengConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @ApiOperation(value="上传文件",notes="上传文件")
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(@ApiParam(value = "上传文件", required = true) @RequestParam("file") MultipartFile file) {
        try
        {
            // 上传并返回新文件名称
            String md5Value = FileUtils.fileMd5(file);
            AjaxResult result = fileUploadUtils.aliyunUpload(file);
            Map<String,String> map = (Map<String,String>)result.get("data");
            //插入文件信息表
            HmFile hmFile = new HmFile();
            hmFile.setFileUrl(map.get("downloadUrl"));
            hmFile.setFileType(map.get("fileSuffix"));
            hmFile.setContentType(map.get("contentType"));
            hmFile.setMd5(md5Value);
            hmFile.setFileName(map.get("fileName"));
            hmFile.setCreateTime(new Date());
            if (map.get("fileSize") != null && !map.get("fileSize").isEmpty() && !map.get("fileSize").equals("null")) {
                hmFile.setFileSize(new Long(map.get("fileSize")));
            }
            if (SecurityUtils.isLogin()) {
                hmFile.setCreateBy(SecurityUtils.getUsername());
            }
            int count = hmFileMapper.insertHmFile(hmFile);
            log.info("成功插入文件名为{}的数据共{}条",map.get("fileName"),count);
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("id",hmFile.getId());
            resultMap.put("fileName",map.get("fileName"));
            resultMap.put("fileType",map.get("fileSuffix"));
            resultMap.put("fileSize",map.get("fileSize"));
            resultMap.put("fileUrl",map.get("downloadUrl"));
            return AjaxResult.success(resultMap);
        }
        catch (Exception e)
        {
            log.error(MessageUtils.message("upload.no")+e.getMessage());
            return AjaxResult.error(MessageUtils.message("upload.no"));
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = HongMengConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 文件下载
     * @param fileId  文件ID
     */
    @ApiOperation(value="文件下载",notes="文件下载")
    @GetMapping(value = "/common/downloadFile")
    @ResponseBody
    public void downloadFile(Integer fileId) {
        hmFileService.downloadFile(fileId);
    }

    /**
     * 文件查询
     * @param fileId 文件ID
     * @return 文件信息
     */
    @ApiOperation(value="文件查询",notes="文件查询")
    @GetMapping(value = "/common/queryFileInfo")
    public AjaxResult queryFileInfo(Integer fileId){
        return AjaxResult.success(hmFileService.selectFileInfo(fileId));
    }

    /**
     * ueditor文件上传（初始化+通用上传）
     */
    @ApiOperation(value="ueditor文件上传（初始化+通用上传）")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "request",value = "request", dataType = "HttpServletRequest"),
            @ApiImplicitParam(name = "response",value = "response", dataType = "HttpServletResponse"),
            @ApiImplicitParam(name = "action",value = "action", dataType = "String")
    })
    @RequestMapping(value = "/common/ueditorUpload",method={RequestMethod.POST,RequestMethod.GET})
    public void ueditorUpload(HttpServletRequest request, HttpServletResponse response, String action) {
        try {
            String rootPath = request.getSession().getServletContext().getRealPath("/");
            if ("config".equals(action)) {    //如果是初始化
                response.setHeader("content-type","text/javascript; charset=uft-8");
                String exec = new ActionEnter(request, rootPath).exec();
                PrintWriter writer = response.getWriter();
                writer.write(exec);
                writer.flush();
                writer.close();
                log.info("ueditor已初始化");
            } else {    //如果是上传图片、视频、和其他文件
                log.info("开始ueditor文件上传");
                try {
                    MultipartHttpServletRequest mul=(MultipartHttpServletRequest)request;
                    Map<String,MultipartFile> files=mul.getFileMap();
                    AjaxResult uploadFile= uploadFile(files.get("upfile"));
                    Map<String,Object> returnMap= (Map<String,Object>) uploadFile.get("data");
                    JSONObject result = new JSONObject();
                    result.put("state", "SUCCESS");
                    result.put("size", returnMap.get("fileSize"));
                    result.put("url", returnMap.get("fileUrl"));
                    result.put("title", returnMap.get("fileName"));
                    result.put("original", returnMap.get("fileName"));
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(result.toString());
                } catch (Exception e) {
                    log.error(e.getMessage(),e);
                }
            }
        } catch (Exception e) {
            log.info("ueditor文件上传:"+e);
        }
    }
}
